Java Comparator vs Comparable


Posted by Rich on 2022-06-23

Both are interface in Java.

Comparable

A comparable object is capable of comparing itself with another object. Comparable implements in the class that you want to sort.

public class Student implements Comparable<Student> {
    private String name;
    private int id;
    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
    @Override
    public int compareTo(Student s) {
        return this.name.compareTo(s.name);
    }
  }

We implement the Comparable interface, so we have to override the compareTo method.
The thing I was confused it's that in the compareTo method, we use another compareTo method. But the method we define takes in Student object as an input, but here it takes String.
It turns out that it's another compareTo method from the String class.

Comparator

We can only sort the instances using one condition if we use the comparable interface. That's why we need comparator if we have multiple conditions.

public class Student {
    private String name;
    private int id;
    Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
  } 
public class SortStudentById implements Comparator<Student> {
        public int compare(Student s1, Student s2) {
        return s1.id - s2.id;
        // if it return a negative number it will move the first element forward.
        //return 0 means no changes in order.
        // return 1 means move the first element backward.
    }
 }









Related Posts

外出學習效果好的一天

外出學習效果好的一天

Bootstrap

Bootstrap

【JS幼幼班】Step.05 基本語法:基本型別(空值、boolean、number)

【JS幼幼班】Step.05 基本語法:基本型別(空值、boolean、number)


Comments